#!/bin/bash
# Fort Knox · ATA — one-click open the app (board console)
URL="http://127.0.0.1:8765/console"
CHROME="/Applications/Google Chrome.app"
PLIST="gui/$(id -u)/com.andrew.trading-board-server"

# Prefer existing board; kickstart LaunchAgent if present
if ! curl -sf --max-time 2 "http://127.0.0.1:8765/api/version" >/dev/null 2>&1; then
  if launchctl print "$PLIST" >/dev/null 2>&1; then
    launchctl kickstart -k "$PLIST" 2>/dev/null || true
    for i in 1 2 3 4 5 6 7 8; do
      sleep 1
      curl -sf --max-time 1 "http://127.0.0.1:8765/api/version" >/dev/null 2>&1 && break
    done
  fi
fi

# Still down? try common install locations for board launcher
if ! curl -sf --max-time 2 "http://127.0.0.1:8765/api/version" >/dev/null 2>&1; then
  HERE="$(cd "$(dirname "$0")/../../.." && pwd)"
  # When inside .app: Contents/MacOS → go up to folder containing the .app
  APP_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
  FOLDER="$(dirname "$APP_DIR")"
  for candidate in \
    "$FOLDER/1_Install/Install_Fort_Knox_EVERYTHING.command" \
    "$FOLDER/1_Install/Restart Fort Knox Board.command" \
    "$HOME/Desktop/MEGAGROKTRON/0_Open_Fort_Knox/Open Fort Knox Console.command"
  do
    if [[ -f "$candidate" ]]; then
      # If never installed, open the installer for them; else restart board
      if [[ "$candidate" == *EVERYTHING* ]]; then
        open "$candidate"
        exit 0
      fi
      bash "$candidate" >/dev/null 2>&1 &
      sleep 2
      break
    fi
  done
fi

# Open the app UI directly
if curl -sf --max-time 2 "http://127.0.0.1:8765/api/version" >/dev/null 2>&1; then
  if [[ -d "$CHROME" ]]; then
    open -a "Google Chrome" --args --app="$URL"
  else
    open "$URL"
  fi
else
  # Last resort: show install folder
  APP_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
  FOLDER="$(dirname "$APP_DIR")"
  if [[ -d "$FOLDER/1_Install" ]]; then
    open "$FOLDER/1_Install"
    osascript -e 'display notification "Run Install_Fort_Knox_EVERYTHING.command, then click GO TO APP again." with title "Fort Knox · ATA"' 2>/dev/null || true
  else
    open "http://127.0.0.1:8765/console" 2>/dev/null || true
  fi
fi
